package com.hnit.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.hnit.configs.AlipayConfig;
import com.hnit.mapper.CouponsMapper;
import com.hnit.mapper.UserCouponsMapper;
import com.hnit.service.CouponService;
import com.hnit.service.OrdersService;
import com.hnit.service.PaymentService;
import com.hnit.web.DTO.OrdersDTO;
import com.hnit.web.Utils.OrderStatus;
import com.hnit.web.bean.UserCoupons;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

@Service
@AllArgsConstructor
@Slf4j
public class PaymentServiceImpl implements PaymentService {
    private final AlipayClient alipayClient;
    private final OrdersService ordersService;
    private final AlipayConfig alipayConfig;
    private final UserCouponsMapper userCouponsMapper;
    @Override
    public String createAlipayOrder(OrdersDTO order) throws Exception {
        try {
            // 创建支付宝扫码支付请求
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();


            // 设置业务参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", order.getOrderId().toString());
            bizContent.put("total_amount", order.getTotalAmount().toString());
            bizContent.put("subject", "订单支付");
            bizContent.put("qr_code_timeout_express", "10m"); // 二维码有效期10分钟

            request.setBizContent(bizContent.toString());

            // 调用支付宝接口
            AlipayTradePrecreateResponse response = alipayClient.execute(request);

            if (response.isSuccess()) {
                log.info("支付宝预下单成功，订单号：{}，二维码：{}", order.getOrderId(), response.getQrCode());
                return generateQrCodeHtml(response.getQrCode(), BigDecimal.valueOf(order.getTotalAmount()));
            } else {
                log.error("支付宝预下单失败，订单号：{}，错误码：{}，错误信息：{}",
                        order.getOrderId(), response.getCode(), response.getMsg());
                throw new RuntimeException("支付宝预下单失败：" + response.getSubMsg());
            }

        } catch (AlipayApiException e) {
            log.error("调用支付宝接口异常，订单号：{}", order.getOrderId(), e);
            throw new RuntimeException("调用支付宝接口失败：" + e.getErrMsg());
        }
    }

    @Override
    public boolean queryPaymentStatus(String orderId) throws Exception {
        try {
            // 创建查询请求
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orderId);
            request.setBizContent(bizContent.toString());

            // 调用支付宝接口查询
            AlipayTradeQueryResponse response = alipayClient.execute(request);

            if (response.isSuccess()) {
                String tradeStatus = response.getTradeStatus();
                log.info("查询支付状态成功，订单号：{}，状态：{}", orderId, tradeStatus);

                // 检查是否支付成功
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    // 更新订单状态
                    ordersService.updateOrderStatus(Long.valueOf(orderId), OrderStatus.PAID_PENDING_SHIP.getCode());
                    // 绑定优惠券
                    // 优惠券处理
                    //查询优惠券表，通过订单id获取是否使用了优惠券
                    UserCoupons userCoupons = null;
                    if (orderId != null) {
                        //查询优惠券表，通过订单id获取是否使用了优惠券
                        userCoupons = userCouponsMapper.selectByOrderId(Long.valueOf(orderId));
                        if (userCoupons == null) {
                            log.debug("未使用优惠券");
                        }else{
                            //将状态设置为已使用
                            userCouponsMapper.updateById(userCoupons.setCouponStatus(2).setUseTime(LocalDateTime.now()));
                        }
                    }
                }
            } else {
                log.warn("查询支付状态失败，订单号：{}，错误：{}", orderId, response.getSubMsg());
            }

            return false;

        } catch (AlipayApiException e) {
            log.error("查询支付状态异常，订单号：{}", orderId, e);
            throw new RuntimeException("查询支付状态失败：" + e.getErrMsg());
        }
    }

    @Override
    public boolean verifyAndHandleNotify(Map<String, String> params) throws Exception {
        try {
            // 验证支付宝签名
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    alipayConfig.getPublicKey(),
                    "UTF-8",
                    "RSA2"
            );

            if (signVerified) {
                String orderId = params.get("out_trade_no");
                String tradeStatus = params.get("trade_status");

                log.info("支付宝异步通知验证成功，订单号：{}，状态：{}", orderId, tradeStatus);

                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    // 更新订单状态
                    ordersService.updateOrderStatus(Long.valueOf(orderId), OrderStatus.PAID_PENDING_SHIP.getCode());
                    return true;
                }
            } else {
                log.warn("支付宝异步通知签名验证失败");
            }

            return false;

        } catch (Exception e) {
            log.error("处理支付宝异步通知异常", e);
            throw e;
        }
    }

    /**
     * 生成二维码HTML页面
     */
    private String generateQrCodeHtml(String qrCode, BigDecimal amount) {
        return "<!DOCTYPE html>" +
                "<html>" +
                "<head><meta charset='UTF-8'><title>支付宝扫码支付</title></head>" +
                "<body style='text-align:center; font-family: Arial, sans-serif;'>" +
                "<div style='padding: 20px;'>" +
                "<h2 style='color: #1677ff;'>请扫码支付</h2>" +
                "<div style='margin: 20px 0;'>" +
                "<img src='" + qrCode + "' style='width: 200px; height: 200px;' />" +
                "</div>" +
                "<p style='font-size: 18px; color: #333;'>支付金额：<span style='color: #f50; font-weight: bold;'>￥" + amount + "</span></p>" +
                "<p style='color: #666;'>请使用支付宝APP扫码支付</p>" +
                "<p style='color: #999; font-size: 12px;'>支付完成后页面将自动跳转</p>" +
                "</div>" +
                "</body>" +
                "</html>";
    }
}